package com.lam.code.base;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ClassUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lam.code.base.domain.BaseEntity;
import com.lam.code.base.domain.ReturnT;
import com.lam.code.utils.PageUtil;
import com.lam.code.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @description 基础Controller
 * @author lam
 * @date 2019/9/26 0:35
 */
@SuppressWarnings("all")
@Slf4j
public abstract class BaseController <S extends BaseService<T>,T extends BaseEntity>
        extends AbstractController implements InitializingBean {
    @Resource
    protected S service;
    private Class<T> clz;

    @Override
    public void afterPropertiesSet() {
        clz = (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 1);
    }

    /**
     * 保存
     * @param request 请求对象
     * @return ReturnT
     */
    @PostMapping("/save")
    @ResponseBody
    public ReturnT save(HttpServletRequest request){
        T t = WebUtil.getParameter(request, clz);
        if (t.getId() == null){
            service.save(t);
            log.info(String.format("添加数据，id[%s]",t.getId()));
        }else{
            service.updateById(t);
            log.info(String.format("修改数据，id[%s]",t.getId()));
        }
        return success();
    }

    /**
     * 根据id获取数据
     * @param id 数据id
     * @return T
     */
    @GetMapping("/load/{id}")
    @ResponseBody
    public T load(@PathVariable Long id){
        Assert.notNull(id,"参数id为空");
        log.debug(String.format("加载数据：id[%s]",id));
        return service.getById(id);
    }

    /**
     * 删除数据
     * @param id 数据id
     * @return T
     */
    @PostMapping("/delete")
    @ResponseBody
    public ReturnT delete(@RequestParam("id") String id){
        Assert.notEmpty(id,"参数id为空");
        this.service.removeByIds(CollUtil.toList(Convert.toLongArray(id.split(","))));
        log.info(String.format("添加数据，id[%s]",id));
        return success();
    }

    /**
     * 分页
     * @param request 请求对象
     * @return ReturnT
     */
    @PostMapping("/page")
    @ResponseBody
    public ReturnT page(HttpServletRequest request) {
        Map<String, Object> paraMap = WebUtil.getParameterMap(request);
        IPage<T> pageData = service.page(PageUtil.getPage(new Page<T>(),paraMap), paraMap);
        return ReturnT.success(pageData.getTotal(),pageData.getRecords());
    }

}
